package cn.uniquesoft.manager;

import java.util.*;

import cn.uniquesoft.util.ContextUtil;


/**
 * 在线用户管理
 *
 * @author zyx
 */
public class ClientManager {

    // 单列模式
    private static ClientManager instance = new ClientManager();

    public static ClientManager getInstance() {
        if (instance == null) {
            instance = new ClientManager();
        }
        return instance;
    }

    // 现在用户map集合<sessionid,client>
    private Map<String, Client> map = new HashMap<String, Client>();

    // 添加在线用户客户端
    public void addClient(String sessionId, Client client) {
        map.put(sessionId, client);
    }

    // 根据sessionid 来删除在线用户信息
    public void removeClient(String sessionId) {
        map.remove(sessionId);
    }

    //删除学生过期sessionid
    public void removeClientOverdue(Client client) {
        try {
            for (String key : map.keySet()) {
                Client client2 = map.get(key);
                boolean flag = false;
               
                if (null != client.getUser()) {
                    if (null != client2.getUser().getCname() && null != client.getUser().getCname()) {
                        flag = client2.getUser().getCname().equals(client.getUser().getCname());
                    }
                }
              

                boolean badddate = null != client2.getAdddate() && null != client.getAdddate() && client2.getAdddate().compareTo(client.getAdddate()) != 0;
                boolean bbrowser = null != client2.getCbrowser() && null != client.getCbrowser() && client2.getCbrowser().equals(client.getCbrowser());
                if (badddate && flag && bbrowser) {
                    map.remove(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 根据sessionid来获取在线用户信息
    public Client getClient(String sessionId) {
        return map.get(sessionId);
    }

    //从系统session中来获取在线用户信息
    public Client getClient() {
        return map.get(ContextUtil.getSession().getId());
    }

    // 获取所有在线用户信息
    public Collection<Client> getAllClient() {
        return map.values();
    }

}
